package com.zhangsun.newMvvm.model.repository;

import com.zhangsun.newMvvm.base.bean.PageBean;
import com.zhangsun.newMvvm.base.bean.ResponseData;
import com.zhangsun.newMvvm.base.model.BaseRepository;
import com.zhangsun.newMvvm.common.network.NetworkManager;
import com.zhangsun.newMvvm.common.network.exception.ApiException;
import com.zhangsun.newMvvm.common.network.listener.HttpCallbackListener;
import com.zhangsun.newMvvm.common.tools.EntityTool;
import com.zhangsun.newMvvm.model.apis.UserApi;
import com.zhangsun.newMvvm.model.bean.UserBean;
import com.zhangsun.newMvvm.model.bean.UserPageBean;

import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class MainRepository extends BaseRepository<ResponseData<PageBean<UserBean>>> {

    public void getUserList(UserPageBean userPage, final HttpCallbackListener<PageBean<UserBean>> callback) {
        UserApi userApi = NetworkManager.getRetrofit().create(UserApi.class);
        Map<String, Object> uMap = EntityTool.entityToMap(userPage);
        setObserver(userApi.getList(uMap), new Observer<ResponseData<PageBean<UserBean>>>() {
            @Override
            public void onSubscribe(Disposable d) {
                addDisposable(d);
            }

            @Override
            public void onNext(ResponseData<PageBean<UserBean>> responseData) {
                if ("success".equals(responseData.getCode())) {
                    callback.onSuccess(responseData);
                } else {
                    callback.onError(responseData);
                }
            }

            @Override
            public void onError(Throwable e) {
                ResponseData responseData = new ResponseData();
                responseData.setCode(((ApiException) e).code);
                responseData.setMessage(((ApiException) e).message);
                callback.onError(responseData);
            }

            @Override
            public void onComplete() {
            }
        });
    }

}
